package com.atguigu.study.controller;

import com.atguigu.study.service.ChatAssistant;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.StreamingResponseHandler;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2025-03-12 16:44
 */

@RestController
@Slf4j
public class ChatLanguageModelController
{
    @Resource
    private StreamingChatLanguageModel streamingChatLanguageModel;
    @Resource
    private ChatAssistant chatAssistant;


    @GetMapping(value = "/chatstream/chat2")
    public Flux<String> chat2(@RequestParam("prompt") String prompt, HttpServletResponse response) {
        // 设置响应的字符编码
        response.setCharacterEncoding("UTF-8");

        chatAssistant.chat2(prompt).subscribe(
                System.out::println,  // onNext
                Throwable::printStackTrace,  // onError
                () -> System.out.println("onComplete")  // onComplete
        );

        /*chatAssistant.chat2(prompt).subscribe(
                str -> {
                    // 这里的代码会在每次有新的String时执行
                    System.out.println(str);
                },
                error -> {
                    // 这里的代码会在发生错误时执行
                    System.err.println("Error occurred: " + error.getMessage());
                },
                () -> {
                    // 这里的代码会在Flux完成时执行
                    System.out.println("All strings processed onComplete.");
                }
        );*/

        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(7); } catch (InterruptedException e) { e.printStackTrace(); }

        return chatAssistant.chat2(prompt);
    }

    @GetMapping(value = "/chatstream/assistant2")
    public void assistant2(@RequestParam(value = "prompt", defaultValue = "hello, 北京有什么好吃的？") String prompt)
    {
        streamingChatLanguageModel.generate(prompt, new StreamingResponseHandler<AiMessage>(){
            @Override
            public void onNext(String token) {
                System.out.println(token);
            }

            @Override
            public void onError(Throwable error) {

            }
        });
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }
    }
}

